package uts.sdk.modules.snUtsAila

import android.content.Intent
import android.os.Handler
import android.os.Message
import com.echo.wificonfig.Aila
import io.dcloud.uts.*

fun <K, V> Map<K, V>.toJSON(): UTSJSONObject = UTSJSONObject(this)

class AilaClient : IAilaClient {
	private var lightCallback: SnUtsAilaCallback? = null
	private val mDeviceHandler by lazy {
		object : Handler() {
			override fun handleMessage(msg: Message) {
				lightCallback?.invoke(
					SnUtsAilaResult(
						code = 0,
						data =
							mapOf<String, Any>(
								"what" to msg.what,
								"arg1" to msg.arg1,
							).toJSON(),
					),
				)
			}
		}
	}

	override fun startService() {
		val activity = UTSAndroid.getUniActivity()!!
		activity.startService(Intent(activity, Aila::class.java))
	}

	override fun onLightHandler(handler: SnUtsAilaCallback) {
		lightCallback = handler
		val activity = UTSAndroid.getUniActivity()!!
		Aila.setLightHandler(activity, mDeviceHandler)
	}

	override fun configWifi(config: AilaConfig) {
		Aila.ConfigWifi(config.mac, config.ssid, config.pass)
	}

	override fun getBleList(callback: SnUtsAilaCallback) {
		callback(
			SnUtsAilaResult(
				0,
				mapOf<String, Any>(
					"list" to
						Aila.mBleList.map {
							mapOf(
								"name" to it.name,
								"mac" to it.mac,
								"connected" to it.connected,
							)
						},
				).toJSON(),
			),
		)
	}
}

object Hybrid {
	private var _client: IAilaClient? = null
	val ailaClient: IAilaClient
		get() {
			if (_client == null) {
				_client = AilaClient()
			}
			return _client!!
		}
}
